package com.cy.pj.sys.web.controller;

import com.cy.pj.common.pojo.JsonResult;
import com.cy.pj.common.util.PageUtil;
import com.cy.pj.sys.pojo.SysUser;
import com.cy.pj.sys.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@RequestMapping("/user/")
@RestController
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;

    @RequiresPermissions("sys:menu:view")
    @GetMapping
    public JsonResult doFindUsers(SysUser entity){
        return new JsonResult(
                PageUtil.startPage().doSelectPageInfo(()->{
                    sysUserService.findUsers(entity);
                }));
    }

    @PostMapping
    public JsonResult doSaveUser(@RequestBody SysUser entity){
        sysUserService.saveUser(entity);
        return new JsonResult("save ok");
    }

    @GetMapping("{id}")
    public JsonResult doFindById(@PathVariable Integer id){
        return new JsonResult(sysUserService.findById(id));
    }

    @PutMapping
    public JsonResult doUpdateUser(@RequestBody SysUser entity){
        sysUserService.updateUser(entity);
        return new JsonResult("update ok");
    }

    @PatchMapping("{id}/{valid}")
//少量数据的更新可使用 Patch 请求,当然使用 put 也可以.
    public JsonResult doValidById(@PathVariable Integer id,
                                  @PathVariable Integer valid){
        sysUserService.validById(id,valid);//update
        return new JsonResult("update ok");
    }

    @GetMapping("/login/{username}/{password}")
    public JsonResult doLogin(@PathVariable String username,
                              @PathVariable String password){
        //控制层拿到账号和密码后会把信息提交给shiro
        //通过subject提交
        //获取subject
        Subject subject = SecurityUtils.getSubject();
        //login方法需要构建UsernamePasswordToken对象
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        token.setRememberMe(true);
        subject.login(token);//提交给 securityManager
        return new JsonResult("login ok");
    }

}
